package com.binest.figureInclusion.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.WildcardQuery;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.binest.common.constant.HttpStatus;
import com.binest.common.core.domain.entity.SysUser;
import com.binest.common.core.domain.model.LoginUser;
import com.binest.common.core.page.TableDataInfo;
import com.binest.common.utils.DateUtils;
import com.binest.common.utils.uuid.IdUtils;
import com.binest.draftBox.domain.DraftBox;
import com.binest.draftBox.mapper.DraftBoxMapper;
import com.binest.figureInclusionMain.domain.FigureInclusionMain;
import com.binest.figureInclusionMain.mapper.FigureInclusionMainMapper;
import com.binest.inclusionExamine.domain.InclusionExamine;
import com.binest.inclusionExamine.mapper.InclusionExamineMapper;
import com.binest.inclusionExamine.service.IInclusionExamineService;
import com.binest.investDetails.domain.InvestDetails;
import com.binest.investDetails.mapper.InvestDetailsMapper;

import com.binest.investDetails.service.IInvestDetailsService;
import com.binest.investorInclusion.domain.InvestorInclusion;
import com.binest.kolInclusion.domain.KolInclusion;
import com.binest.socialMediaConnection.domain.SocialMediaConnection;
import com.binest.socialMediaConnection.mapper.SocialMediaConnectionMapper;
import com.binest.socialMediaConnection.service.ISocialMediaConnectionService;
import com.binest.universityInformation.domain.UniversityInformation;
import com.binest.universityInformation.service.IUniversityInformationService;
import com.binest.workExperience.domain.WorkExperience;
import com.binest.workExperience.mapper.WorkExperienceMapper;
import com.binest.workExperience.service.IWorkExperienceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.binest.figureInclusion.mapper.FigureInclusionMapper;
import com.binest.figureInclusion.domain.FigureInclusion;
import com.binest.figureInclusion.service.IFigureInclusionService;

import static com.binest.common.utils.SecurityUtils.getLoginUser;

/**
 * 人物收录Service业务层处理
 *
 * @author wwd
 * @date 2024-01-18
 */
@Service
public class FigureInclusionServiceImpl implements IFigureInclusionService {
    @Autowired
    private FigureInclusionMapper figureInclusionMapper;
    @Autowired
    private SocialMediaConnectionMapper socialMediaConnectionMapper;
    @Autowired
    private IInclusionExamineService inclusionExamineService;
    @Autowired
    private FigureInclusionMainMapper figureInclusionMainMapper;

    @Autowired
    private DraftBoxMapper draftBoxMapper;

    @Autowired
    private InclusionExamineMapper inclusionExamineMapper;


    @Autowired
    private WorkExperienceMapper workExperienceMapper;
    @Autowired
    private InvestDetailsMapper investDetailsMapper;

    @Autowired
    private ElasticsearchClient client;

    @Autowired
    private ISocialMediaConnectionService socialMediaConnectionService;


    @Autowired
    private IInvestDetailsService investDetailsService;

    @Autowired
    private IWorkExperienceService workExperienceService;
    @Autowired
    private IUniversityInformationService universityInformationService;
    /**
     * 查询人物收录
     *
     * @param id 人物收录主键
     * @return 人物收录
     */
    @Override
    public FigureInclusion selectFigureInclusionById(String id) {

        FigureInclusion res=figureInclusionMapper.selectFigureInclusionById(id);
          String school="";
         String [] arr=res.getEducationExp().split(",");
         for(int a=0;a<arr.length;a++)
         {
             UniversityInformation un= universityInformationService.selectUniversityInformationById(arr[a]);
             school +=un.getName()+"  ";
         }
        res.setEducationExp(school);
        List<SocialMediaConnection> smcList=socialMediaConnectionService.selectSocialMediaConnectionByInId(id);
        if(smcList!=null)
        {
            res.setSmcList(smcList);
        }
        List<WorkExperience> workExperienceList =workExperienceService.selectWorkExperienceByExpId(id);
        if(workExperienceList!=null)
        {
            res.setWorkExperienceList(workExperienceList);
        }
        // 投资详情
        List<InvestDetails> investDetailsList=investDetailsService.selectInvestDetailsListByInId(id);
        if(investDetailsList!=null)
        {
            res.setInvestDetailsList(investDetailsList);
        }
        return  res;
    }

    @Override
    public FigureInclusion selectEsFigureInclusionById(String id) throws Exception {
        FigureInclusion res = new FigureInclusion();
        try {
            // 执行查询
            SearchResponse<FigureInclusion> searchResponse = client.search(srBuilder -> srBuilder
                            .index("figure_inclusion")
                            // 多个id查询
                            .query(queryBuilder -> queryBuilder
                                    .ids(idsQueryBuilder -> idsQueryBuilder
                                            .values(id))
                            )
                    , FigureInclusion.class);

            //解析查询结果
            List<Hit<FigureInclusion>> hitList = searchResponse.hits().hits();
            res = hitList.get(0).source();

        } catch (IOException e) {
            throw new Exception("查询ES数据失败");

        }


        return res;
    }

    /**
     * 查询人物收录列表
     *
     * @param figureInclusion 人物收录
     * @return 人物收录
     */
    @Override
    public List<FigureInclusion> selectFigureInclusionList(FigureInclusion figureInclusion) {


        List<FigureInclusion> resList=figureInclusionMapper.selectFigureInclusionList(figureInclusion);
        for(FigureInclusion p:resList){
            String   exStatus= inclusionExamineService.getExamineStatus(p.getId());
            if(exStatus!=null){
                p.setExStatus(exStatus);
            }else{
                p.setExStatus("");
            }
        }

        return resList;

    }

    /**
     * 查询es中审核通过的收录
     * @param figureInclusion
     * @return
     * @throws Exception
     */
    @Override
    public TableDataInfo selectFigureInclusionEsList(FigureInclusion figureInclusion) throws Exception {
        TableDataInfo rspData = new TableDataInfo();
        // 将多个查询条件放入list中.
        List<Query> queries = new ArrayList<>();
        List<Query> querie = new ArrayList<>();

        //最新 最热
        String type = "";
        if (figureInclusion.getType().equals("0")) {
            //最新
            type = "createTime.keyword";
        } else {
            type = "likeCount.keyword";
        }
        // 升序降序
        String esSort = "";

        if (figureInclusion.getSort().equals("0")) {
            //最新
            esSort = "Desc";
        } else {
            esSort = "Asc";
        }

        //判断中英文  0英文  1中文
        Query byLang = MatchQuery.of(a -> a
                .field("lang")
                .query(figureInclusion.getLang())
        )._toQuery();

        querie.add(byLang);

        //查询条件  关键词模糊查询
        if (figureInclusion.getName() != null) {

            Query byName = WildcardQuery.of(m -> m
                    .field("name")
                    .value("*" + figureInclusion.getName() + "*")

            )._toQuery();

            Query byContent = WildcardQuery.of(m -> m
                    .field("content")
                    .value("*" + figureInclusion.getName() + "*")

            )._toQuery();


            queries.add(byName);
            queries.add(byContent);

        }
        try {
            // 从es中根据条件查询结果.
            String finalType = type;
            String finalEsSort = esSort;
            SearchResponse<FigureInclusion> searchResponse = client.search(s -> s
                            .index("figure_inclusion")
                            .query(q -> q
                                    .bool(t -> t
                                            .should(queries)
                                            .must(querie)

                                    ))
                            .from((figureInclusion.getPageNum() - 1) * figureInclusion.getPageSize())
                            .size(figureInclusion.getPageSize())
                            .sort(sort -> sort.field(f -> f.field(finalType).order(SortOrder.valueOf(finalEsSort))))
                    , FigureInclusion.class);
            List<Hit<FigureInclusion>> hitList = searchResponse.hits().hits();

            List<FigureInclusion> list = new ArrayList<>();
            for (Hit<FigureInclusion> mapHit : hitList) {
                list.add(mapHit.source());
            }

            long total = searchResponse.hits().total() != null ? searchResponse.hits().total().value() : 0;

            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(list);
            rspData.setTotal(total);

            return rspData;
        } catch (Exception e) {
            throw new Exception("【查询 -> 失败】从es中组合查询出错，错误信息为：{}");
        }
    }

    /**
     * 新增人物收录
     *
     * @param figureInclusion 人物收录
     * @return 结果
     */
    @Override
    public String insertFigureInclusion(FigureInclusion figureInclusion) {
        figureInclusion.setCreateTime(DateUtils.getNowDate());

        //判断存草稿箱还是提交收录
        //存草稿箱
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();

        //判断是否有主表id
        if (figureInclusion.getMainId() == null) {


            String uuid = IdUtils.simpleUUID();
            String mainId = IdUtils.simpleUUID();
            figureInclusion.setId(uuid);
            figureInclusion.setMainId(mainId);
            figureInclusion.setCreateTime(DateUtils.getNowDate());
            figureInclusion.setCreateBy(currentUser.getUserId().toString());

            //新增社交媒体链接
            if (figureInclusion.getSmcList() != null) {

                for (SocialMediaConnection s : figureInclusion.getSmcList()) {


                    s.setId(IdUtils.simpleUUID());
                    //收录id
                    s.setInclusionId(uuid);
                    s.setCreateBy(currentUser.getUserId().toString());
                    s.setCreateTime(DateUtils.getNowDate());
                    socialMediaConnectionMapper.insertSocialMediaConnection(s);
                }
            }

            //工作经历
            if (figureInclusion.getWorkExperienceList() != null) {

                for (WorkExperience w : figureInclusion.getWorkExperienceList()) {


                    w.setId(IdUtils.simpleUUID());
                    w.setCreateBy(currentUser.getUserId().toString());
                    w.setCreateTime(DateUtils.getNowDate());
                    w.setInclusionId(figureInclusion.getId());
                    workExperienceMapper.insertWorkExperience(w);
                }
            }
            //投资详情
            if (figureInclusion.getInvestDetailsList() != null) {
                for (InvestDetails i : figureInclusion.getInvestDetailsList()) {

                    i.setId(IdUtils.simpleUUID());
                    //收录id
                    i.setInclusionId(uuid);
                    i.setCreateBy(currentUser.getUserId().toString());
                    i.setCreateTime(DateUtils.getNowDate());
                    investDetailsMapper.insertInvestDetails(i);
                }
            }

            //新增人物收录
            figureInclusionMapper.insertFigureInclusion(figureInclusion);
            //新增人物收录主表
            FigureInclusionMain figureInclusionMain = new FigureInclusionMain();
            figureInclusionMain.setId(mainId);
            figureInclusionMain.setCreateTime(DateUtils.getNowDate());
            figureInclusionMain.setCreateBy(currentUser.getUserId().toString());
            figureInclusionMainMapper.insertFigureInclusionMain(figureInclusionMain);


            if (figureInclusion.getSubmitType().equals("0")) {

                DraftBox draftBox = new DraftBox();
                draftBox.setId(IdUtils.simpleUUID());
                //人物名称
                draftBox.setName(figureInclusion.getName());
                //类型  人物收录
                draftBox.setType("2");
                draftBox.setProjectId(uuid);
                draftBox.setUserId(currentUser.getUserId().toString());
                draftBox.setCreateBy(currentUser.getUserId().toString());
                draftBox.setCreateTime(DateUtils.getNowDate());
                draftBoxMapper.insertDraftBox(draftBox);
            } else {

                InclusionExamine inclusionExamine = new InclusionExamine();

                inclusionExamine.setId(IdUtils.simpleUUID());
                //未审核
                inclusionExamine.setStatus("0");
                inclusionExamine.setName(figureInclusion.getName());
                //类型 人物收录
                inclusionExamine.setType("2");
                inclusionExamine.setProjectId(uuid);
                inclusionExamine.setUserId(currentUser.getUserId().toString());
                inclusionExamine.setCreateBy(currentUser.getUserId().toString());
                inclusionExamine.setCreateTime(DateUtils.getNowDate());
                inclusionExamineMapper.insertInclusionExamine(inclusionExamine);


            }


        } else {
            String uuid = IdUtils.simpleUUID();
            figureInclusion.setId(uuid);
            figureInclusion.setCreateTime(DateUtils.getNowDate());
            figureInclusion.setCreateBy(currentUser.getUserId().toString());

            //新增kol收录
            figureInclusionMapper.insertFigureInclusion(figureInclusion);
            //新增社交媒体链接
            if (figureInclusion.getSmcList() != null) {

                for (SocialMediaConnection s : figureInclusion.getSmcList()) {


                    s.setId(IdUtils.simpleUUID());
                    //收录id
                    s.setInclusionId(uuid);
                    s.setCreateBy(currentUser.getUserId().toString());
                    s.setCreateTime(DateUtils.getNowDate());
                    socialMediaConnectionMapper.insertSocialMediaConnection(s);
                }

            }
            if (figureInclusion.getWorkExperienceList() != null) {

                for (WorkExperience w : figureInclusion.getWorkExperienceList()) {


                    w.setId(IdUtils.simpleUUID());
                    w.setCreateBy(currentUser.getUserId().toString());
                    w.setInclusionId(figureInclusion.getId());
                    w.setCreateTime(DateUtils.getNowDate());
                    workExperienceMapper.insertWorkExperience(w);
                }
            }
            //投资详情
            if (figureInclusion.getInvestDetailsList() != null) {
                for (InvestDetails i : figureInclusion.getInvestDetailsList()) {

                    i.setId(IdUtils.simpleUUID());
                    //收录id
                    i.setInclusionId(uuid);
                    i.setCreateBy(currentUser.getUserId().toString());
                    i.setCreateTime(DateUtils.getNowDate());
                    investDetailsMapper.insertInvestDetails(i);
                }
            }

            if (figureInclusion.getSubmitType().equals("0")) {

                DraftBox draftBox = new DraftBox();
                draftBox.setId(IdUtils.simpleUUID());
                //kol昵称
                draftBox.setName(figureInclusion.getName());
                //类型  人物收录
                draftBox.setType("2");
                draftBox.setProjectId(uuid);
                draftBox.setUserId(currentUser.getUserId().toString());
                draftBox.setCreateBy(currentUser.getUserId().toString());
                draftBox.setCreateTime(DateUtils.getNowDate());
                draftBoxMapper.insertDraftBox(draftBox);
            } else {

                InclusionExamine inclusionExamine = new InclusionExamine();

                inclusionExamine.setId(IdUtils.simpleUUID());
                //未审核
                inclusionExamine.setStatus("0");
                inclusionExamine.setName(figureInclusion.getName());
                //类型 人物收录
                inclusionExamine.setType("2");
                inclusionExamine.setProjectId(uuid);
                inclusionExamine.setUserId(currentUser.getUserId().toString());
                inclusionExamine.setCreateBy(currentUser.getUserId().toString());
                inclusionExamine.setCreateTime(DateUtils.getNowDate());
                inclusionExamineMapper.insertInclusionExamine(inclusionExamine);

            }

        }
        return figureInclusion.getMainId();
    }

    /**
     * 修改人物收录
     *
     * @param figureInclusion 人物收录
     * @return 结果
     */
    @Override
    public int updateFigureInclusion(FigureInclusion figureInclusion) {
        figureInclusion.setUpdateTime(DateUtils.getNowDate());
        return figureInclusionMapper.updateFigureInclusion(figureInclusion);
    }

    /**
     * 批量删除人物收录
     *
     * @param ids 需要删除的人物收录主键
     * @return 结果
     */
    @Override
    public int deleteFigureInclusionByIds(String[] ids) {
        return figureInclusionMapper.deleteFigureInclusionByIds(ids);
    }

    /**
     * 删除人物收录信息
     *
     * @param id 人物收录主键
     * @return 结果
     */
    @Override
    public int deleteFigureInclusionById(String id) {
        return figureInclusionMapper.deleteFigureInclusionById(id);
    }
}
